package com.gyp.config;

import cn.hutool.core.date.StopWatch;
import com.gyp.anno.ExcludeLogging;
import com.gyp.anno.LogPrint;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author xyb
 * @Description 日志打印切面
 * @since 9:37 2022/7/18
 */
@Component
@Slf4j
@Aspect
public class LogPrintAspect {

    @Pointcut("execution(* com.gyp.controller..*.*(..))")
    public void printLog() {

    }

    @Around(value = "printLog()")
    public Object intercept(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        ExcludeLogging logPrint = method.getAnnotation(ExcludeLogging.class);
        if (Objects.nonNull(logPrint)) {
            // 执行原始方法
            Object result = joinPoint.proceed();
            return result;
        } else {
            Object[] args = joinPoint.getArgs();
            String[] paramsName = signature.getParameterNames();
            StringBuilder sb = new StringBuilder("request:[");
            if (args != null && paramsName != null && args.length > 0 && paramsName.length > 0) {
                for (int i = 0; i < paramsName.length; i++) {
                    sb.append(" ").append(paramsName[i]).append(" = ").append(args[i]).append(",");
                }
                sb.deleteCharAt(sb.length() - 1);
            }
            sb.append("]");
            log.info(sb.toString());
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            Object result = joinPoint.proceed();
            stopWatch.stop();
            long cost = stopWatch.getTotalTimeMillis();
            log.info("[response:{}][cost:{}]",result,cost);
            return result;
        }
    }


}
